package shujia.day14.jdbc;

import java.sql.*;
import java.util.Scanner;

/*
    JDBC 解决sql注入的问题
 */
public class JDBCDemo2 {
    public static void main(String[] args) {
        login();
    }

    public static Connection getConnection() {
        Connection conn = null;
        try {
            //1、加载驱动类
            // mysql驱动包5.1.xx版本中驱动类的路径：com.mysql.jdbc.Driver
            // mysql驱动包8.0.xx版本中驱动类的路径：com.mysql.cj.jdbc.Driver
            Class.forName("com.mysql.jdbc.Driver");

            //2、创建数据库连接对象
            //public static Connection getConnection(String url,String user, String password)
            /*
                url: 指定要连接的mysql服务地址以及数据库名
                    jdbc:mysql://master:3306/bigdata33?useUnicode=true&characterEncoding=utf-8
             */
            String url = "jdbc:mysql://master:3306/bigdata33?useUnicode=true&characterEncoding=utf-8&useSSL=false";
            String username = "root";
            String password = "123456";
            conn = DriverManager.getConnection(url, username, password);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return conn;
    }

    public static void login() {
        try {
            Scanner sc = new Scanner(System.in);
            System.out.println("请输入您的用户名：");
            String name = sc.nextLine();
            System.out.println("请输入您的密码：");
            String password = sc.nextLine();

            Connection conn = getConnection();
//            Statement state = conn.createStatement(); // 先传值，再编译sql语句
//
//            ResultSet resultSet = state.executeQuery("select * from users where name='" + name + "' and password='" + password + "'");
//            //select * from users where name='小虎' and password='1' or '1'='1';
//            if(resultSet.next()){
//                System.out.println("登录成功！！");
//            }else {
//                System.out.println("登录失败！！");
//            }

            //防止sql注入，需要创建预编译对象来执行sql语句，先编译sql语句，再传值
            PreparedStatement preparedStatement = conn.prepareStatement("select * from users where name=? and password=?");
            //设置？传值
            preparedStatement.setString(1, name);
            preparedStatement.setString(2, password);
            ResultSet resultSet = preparedStatement.executeQuery();
            if (resultSet.next()) {
                System.out.println("登录成功！！");
            } else {
                System.out.println("登录失败！！");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}
